<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="50%"
    :before-close="handleClose"
  >
    <div class="freight-dialog">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input
            placeholder="输入模板名称"
            style="width: 100%"
            v-model="ruleForm.name"
          />
        </el-form-item>
        <el-form-item v-if="ruleForm.id" label="模板编号" prop="code">
          <el-input
            disabled
            placeholder="输入模板编号"
            style="width: 100%"
            v-model="ruleForm.code"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group
            v-model="ruleForm.status"
            :disabled="ruleForm.id ? true : false"
          >
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input
            placeholder="排序"
            style="width: 100%"
            v-model="ruleForm.sort"
          />
        </el-form-item>
        <el-form-item label="计费方式" prop="type" style="width: 100%">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="1">按件数</el-radio>
            <el-radio :label="2">按重量</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="计费规则"
          style="width: 100%; margin-bottom: 0px"
        />
        <div style="padding: 0 25px; margin-bottom: 15px">
          <el-button
            style="margin: 10px 0"
            size="small"
            type="primary"
            @click="openType"
            >添加</el-button
          >
          <el-table border stripe :data="topTable">
            <el-table-column label="可配送区域" prop="area" />
            <el-table-column label="首件/重" prop="firstNum" width="100" />
            <el-table-column label="运费(元)" prop="firstAmt" width="100" />
            <el-table-column label="续件/重" prop="repeatNum" width="100" />
            <el-table-column label="续费(元)" prop="repeatAmt" width="100" />
            <el-table-column label="操作" width="110">
              <template #default="scoped">
                <el-button type="primary" link @click="updateTypeFun(scoped)">
                  编辑
                </el-button>
                <el-button type="danger" link @click="delTypeFun(scoped)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item
          label="指定包邮"
          prop="appoint"
          style="width: 100%; margin-bottom: 0"
        >
          <el-radio-group v-model="ruleForm.appoint">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div
          style="padding: 0 25px; margin-bottom: 15px"
          v-if="ruleForm.appoint === 0"
        >
          <el-button
            style="margin: 10px 0"
            size="small"
            type="primary"
            @click="openPost"
            >添加</el-button
          >
          <el-table border stripe :data="bottomTable">
            <el-table-column label="可配送区域" prop="area" />
            <el-table-column label="包邮件数" prop="sNum" width="100" />
            <el-table-column label="包邮金额(元)" prop="sPrice" width="120" />
            <el-table-column label="操作" width="110">
              <template #default="scoped">
                <el-button type="primary" link @click="updatePostFun(scoped)">
                  编辑
                </el-button>
                <el-button type="danger" link @click="delPostFun(scoped)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
  <dialogAdd
    ref="addRulesRef"
    :treeData="treeData"
    @refreshType="refreshType"
  />
  <dialogAdd2
    ref="addRules2Ref"
    :treeData="treeData"
    @refreshPost="refreshPost"
  />
</template>
<script setup>
import { addApi } from "@/plugins/api/shopping/freight";
import { listApi as areaApi } from "@/plugins/api/shopping/area";
import dialogAdd from "./DialogFreight-child-1.vue";
import dialogAdd2 from "./DialogFreight-child-2.vue";
let ruleForm = ref({
  status: 1,
});
let rules = {
  name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择计费方式", trigger: "change" }],
  appoint: [{ required: true, message: "请选择邮递方式", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  topTable.value = [];
  bottomTable.value = [];
  if (type == "add") {
    title.value = "新增";
    ruleForm.value = {};
    ruleForm.value.type = 1;
    ruleForm.value.appoint = 0;
    ruleForm.value.status = 1;
  } else {
    title.value = "编辑";
    ruleForm.value = Object.assign({}, row);

    if (row.content) {
      row.content.forEach((item) => {
        let obj = Object.assign({}, item.rule);
        if (item.city && item.city.length > 0) {
          obj.city = [].concat(item.city);
          obj.area = areaDataChange(item.city);
        } else {
          obj.area = "全国";
        }
        topTable.value.push(obj);
      });
    }

    if (row.free) {
      row.free.forEach((item) => {
        let obj = Object.assign({}, item.rule);
        if (item.city && item.city.length > 0) {
          obj.city = [].concat(item.city);
          obj.area = areaDataChange(item.city);
        } else {
          obj.area = "全国";
        }
        bottomTable.value.push(obj);
      });
    }
  }

  dialogVisible.value = true;
}
function areaDataChange(arr) {
  if (!Array.isArray(arr)) return;
  let parentList = [];
  arr.forEach((item) => {
    let p_obj = findParen(treeData.value, item.pid);

    if (p_obj) {
      if (
        !parentList.some((ele) => {
          return ele.id == p_obj.id;
        })
      ) {
        parentList.push(p_obj);
      }
    }
  });
  return parentList
    .map((item) => {
      return item.name;
    })
    .join(",");
}

const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let obj = Object.assign({}, ruleForm.value);
      // 计费规则
      if (topTable.value.length == 0) {
        return ElMessage.warning("请填写计费规则！");
      }
      obj.content = topDataChange();
      //是否包邮
      if (ruleForm.value.appoint === 0) {
        if (bottomTable.value.length == 0) {
          return ElMessage.warning("已选择指定包邮，请选择配送区域！");
        }
        obj.free = bottomDataChange();
      } else {
        obj.free = [];
      }

      if (!ruleForm.value.id) {
        addApi(obj).then((data) => {
          ElMessage.success("新增成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      } else {
        addApi(obj).then((data) => {
          ElMessage.success("修改成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      }
    }
  });
}
// 地区数据
let treeData = ref([]);
function getData() {
  areaApi({}).then((data) => {
    treeData.value = data;
  });
}
//
let addRulesRef = ref(null);
let ruleType = ref(null);
let topIndex = ref(null);
function openType() {
  ruleType.value = "add";
  addRulesRef.value.initFun("add");
}
let topTable = ref([]);
// 新增配送区域
function refreshType(obj) {
  let new_data = {};
  new_data = Object.assign({}, obj);
  let parentArr = [];
  let itemArr = [];
  if (obj.area) {
    obj.area.forEach((item) => {
      let p_obj = findParen(treeData.value, item);

      if (p_obj) {
        if (
          !parentArr.some((ele) => {
            return ele.id == p_obj.id;
          })
        ) {
          parentArr.push(p_obj);
        }
      }
      let s_obj = findSelf(treeData.value, item);
      if (s_obj) {
        itemArr.push(s_obj);
      }
    });
  }
  if (parentArr.length == 0) {
    new_data.area = "全国";
  } else {
    new_data.area = parentArr
      .map((item) => {
        return item.name;
      })
      .join(",");
    new_data.city = itemArr;
  }
  if (ruleType.value == "add") {
    topTable.value.push(new_data);
  } else {
    topTable.value.splice(topIndex.value, 1, new_data);
  }
}

// 编辑
function updateTypeFun(scoped) {
  topIndex.value = scoped.$index;

  ruleType.value = "update";
  addRulesRef.value.initFun("update", scoped.row);
}
function delTypeFun(scoped) {
  topTable.value.splice(scoped.$index, 1);
}

function findParen(tree, pid) {
  for (const node of tree) {
    if (node.id === pid) {
      return node; // 找到匹配的父节点
    }
    if (node.sub && node.sub.length > 0) {
      const result = findParen(node.sub, pid);
      if (result) {
        return node; // 找到匹配的父节点
      }
    }
  }
  return null; // 没有找到匹配的父节点
}
function findSelf(tree, id) {
  for (const node of tree) {
    if (node.id === id) {
      return node;
    }
    if (node.sub && node.sub.length > 0) {
      const result = findSelf(node.sub, id);
      if (result) {
        return result;
      }
    }
  }
  return null; // 没有找到匹配的父节点
}
function topDataChange() {
  let arr = [];
  if (topTable.value.length > 0) {
    topTable.value.forEach((item) => {
      let content = {};
      let city = item.city;
      let rule = {
        firstAmt: item.firstAmt,
        firstNum: item.firstNum,
        repeatAmt: item.repeatAmt,
        repeatNum: item.repeatNum,
      };
      content.city = city;
      content.rule = rule;
      arr.push(content);
    });
  }
  return arr;
}
// 包邮模块----------------------------------------------------------------
let addRules2Ref = ref(null);
let bottomIndex = ref(null);
let postType = ref(null);
function openPost() {
  postType.value = "add";
  addRules2Ref.value.initFun("add");
}
let bottomTable = ref([]);

function refreshPost(obj) {
  let new_data = {};
  new_data = Object.assign({}, obj);
  let parentArr = [];
  let itemArr = [];
  if (obj.area) {
    obj.area.forEach((item) => {
      let p_obj = findParen(treeData.value, item);
      if (p_obj) {
        if (
          !parentArr.some((ele) => {
            return ele == p_obj;
          })
        ) {
          parentArr.push(p_obj);
        }
      }
      let s_obj = findSelf(treeData.value, item);
      if (s_obj) {
        itemArr.push(s_obj);
      }
    });
  }
  if (parentArr.length == 0) {
    new_data.area = "全国";
  } else {
    new_data.area = parentArr
      .map((item) => {
        return item.name;
      })
      .join(",");
    new_data.city = itemArr;
  }
  if (postType.value == "add") {
    bottomTable.value.push(new_data);
  } else {
    bottomTable.value.splice(bottomIndex.value, 1, new_data);
  }
}

function updatePostFun(scoped) {
  postType.value = "update";
  bottomIndex.value = scoped.$index;
  addRules2Ref.value.initFun("update", scoped.row);
}
function delPostFun(scoped) {
  bottomTable.value.splice(scoped.$index, 1);
}
function bottomDataChange() {
  let arr = [];
  if (bottomTable.value.length > 0) {
    bottomTable.value.forEach((item) => {
      let content = {};
      let city = item.city;
      let rule = {
        sNum: item.sNum,
        sPrice: item.sPrice,
      };
      content.city = city;
      content.rule = rule;
      arr.push(content);
    });
  }
  return arr;
}
onMounted(() => {
  getData();
});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.freight-dialog {
  :deep(.el-form-item) {
    width: calc(50% - 10px);
    margin-right: 10px;
  }
  :deep(.table-form-item) {
    .el-form-item__label {
      width: 150px !important;
      margin-left: 10px !important;
    }
  }
}
</style>
